package com.hmyd.hmyd_android.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.adapter.MessageAdapter;
import com.hmyd.hmyd_android.adapter.MessageAdapter.onMsgSelectListener;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.Message;
import com.hmyd.hmyd_android.dto.Page;
import com.hmyd.hmyd_android.view.listview.XListView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 我的消息
 * 
 * @author wangc
 * 
 */
@ContentView(R.layout.activity_my_message)
public class MessageListActivity extends BasicListActivity implements OnItemLongClickListener,
		onMsgSelectListener {

	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;

	@ViewInject(R.id.message_list)
	private XListView mList;

	@ViewInject(R.id.message_list_edit)
	private RelativeLayout editLayout;

	@ViewInject(R.id.message_btn_all_read)
	private Button mBtnAllRead;

	@ViewInject(R.id.message_btn_del)
	private Button mBtnDel;

	@ViewInject(R.id.message_btn_all)
	private Button mBtnAll;

	private final int REFRESH = 1;
	private final int LOADMORE = 2;
	private final int DELETE = 3;
	private final int READED = 4;
	protected boolean hasMore = false;
	private String cursorId;
	// private int delPosition;

	private List<Message> datas = new ArrayList<Message>();
	private MessageAdapter mAdapter;
	private List<String> idStrings = new ArrayList<String>();

	@OnClick({ R.id.home_right, R.id.message_btn_del, R.id.message_btn_all_read,
			R.id.message_btn_all })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.home_right:
			if ("编辑".equals(home_right.getText().toString().trim())) {
				mAdapter.isCheck = false;
				mAdapter.isShow = true;
				mAdapter.notifyDataSetChanged();
				mList.setAdapter(mAdapter);
				home_right.setText("取消");
				editLayout.setVisibility(View.VISIBLE);
			} else if ("取消".equals(home_right.getText().toString().trim())) {
				mAdapter.isShow = false;
				mAdapter.isCheck = false;
				mAdapter.notifyDataSetChanged();
				mList.setAdapter(mAdapter);
				home_right.setText("编辑");
				editLayout.setVisibility(View.GONE);
			}
			break;
		case R.id.message_btn_all_read:// 全部已读
			editLayout.setVisibility(View.GONE);
			home_right.setText("编辑");
			mAdapter.isShow = false;
			mAdapter.isCheck = false;
			mAdapter.notifyDataSetChanged();
			RequestParams params = new RequestParams();
			for (int i = 0; i < idStrings.size(); i++) {
				params.addBodyParameter("messageIds", idStrings.get(i));
			}
			onRequest(READED, UrlConstant.READED, HttpMethod.GET, params);
			break;
		case R.id.message_btn_del:// 删除
			editLayout.setVisibility(View.GONE);
			home_right.setText("编辑");
			mAdapter.isShow = false;
			mAdapter.isCheck = false;
			mAdapter.notifyDataSetChanged();
			RequestParams params1 = new RequestParams();
			for (int i = 0; i < idStrings.size(); i++) {
				params1.addBodyParameter("messageIds", idStrings.get(i));
			}
			onRequest(DELETE, UrlConstant.DEL_MESSAGE, HttpMethod.GET, params1);
			break;
		case R.id.message_btn_all:// 全选
			mAdapter.isCheck = true;
			mAdapter.notifyDataSetChanged();
			break;

		default:
			break;
		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		init();
	}

	private void init() {
		mAdapter = new MessageAdapter(this, datas);
		mList.setAdapter(mAdapter);

		mList.setPullRefreshEnable(true); // 允许下拉刷新
		mList.setPullLoadEnable(false); // 禁止加载更多
		mList.setAutoLoadEnable(false); // 禁止自动加载
		mList.setXListViewListener(this);// 加载监听

		mList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				idStrings.clear();
				RequestParams params = new RequestParams();
				params.addBodyParameter("messageIds", datas.get(position - 1).messageId);
				onRequest(READED, UrlConstant.READED, HttpMethod.GET, params);
				idStrings.add(datas.get(position - 1).messageId);
			}
		});
	}

	public XListView getXList() {
		return mList;
	}

	@Override
	protected void onResume() {
		super.onResume();

		onRequest(REFRESH, UrlConstant.MESSAGELIST, HttpMethod.GET, null);
	}

	@Override
	public void onPostSuccess(int postId, String result) {

		super.onPostSuccess(postId, result);
		Gson gson = new Gson();
		java.lang.reflect.Type type2 = new TypeToken<Page<Message>>() {
		}.getType();
		Page<Message> page = gson.fromJson(result, type2);
		hasMore = page.hasMore;
		if (postId == DELETE) {
			for (int i = 0; i < idStrings.size(); i++) {
				for (int j = 0; j < datas.size(); j++) {
					if (idStrings.get(i).equals(datas.get(j).messageId)) {
						datas.remove(datas.get(j));
					}
				}
			}
			mAdapter.notifyDataSetChanged();
		}

		if (postId == READED) {
			for (int i = 0; i < idStrings.size(); i++) {
				for (int j = 0; j < datas.size(); j++) {
					if (idStrings.get(i).equals(datas.get(j).messageId)) {
						datas.get(j).unread = false;
					}
				}
			}
			mAdapter.notifyDataSetChanged();
		}

		if (page != null && page.records != null) {

			switch (postId) {
			case REFRESH:
				datas.clear();
				datas.addAll(page.records);
				break;
			case LOADMORE:
				datas.addAll(page.records);
				break;
			default:
				break;
			}

			if (datas.size() > 0) {
				cursorId = datas.get(datas.size() - 1).cursorId;
			} else {
				cursorId = null;
			}

			mAdapter.notifyDataSetChanged();

		}

		if (getXList() != null && hasMore) {
			getXList().setPullLoadEnable(true);
		} else if (getXList() != null && !hasMore) {
			getXList().setPullLoadEnable(false);
		}

	}

	@Override
	public void onPostFailure(int postId, String msg) {
		if (getXList() != null && hasMore) {
			getXList().setPullLoadEnable(true);
		} else if (getXList() != null && !hasMore) {
			getXList().setPullLoadEnable(false);
		}

	}

	@Override
	protected void setParams() {
		home_title_txt.setText("我的消息");
		home_right.setText("编辑");
		home_right.setFocusable(true);
		home_title.setOnTouchListener(touch);
	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {

	}

	@Override
	public void onRefresh() {
		super.onRefresh();

		onRequest(REFRESH, UrlConstant.MESSAGELIST, HttpMethod.GET, null);
	}

	@Override
	public void onLoadMore() {
		super.onLoadMore();

		RequestParams params = new RequestParams();
		params.addBodyParameter("lastCursor", cursorId);

		onRequest(LOADMORE, UrlConstant.MESSAGELIST, HttpMethod.GET, params);
	}

	// 长按删除
	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
		// NormalDialog cd = new NormalDialog(getApplicationContext(),
		// R.style.calculatorDialog,
		// new NormalDialogListener() {
		// @Override
		// public void ok() {
		// deleteMessage();
		//
		// }
		//
		// private void deleteMessage() {
		// String messageId = datas.get(position - 1).messageId;
		// delPosition = position - 1;
		// RequestParams params = new RequestParams();
		// params.addBodyParameter("messageId", messageId);
		// onRequest(DELETE, UrlConstant.DEL_MESSAGE, HttpMethod.GET, params);
		// }
		//
		// @Override
		// public void cancle() {
		//
		// }
		//
		// }, "提示", "是否要删除该条消息？", "删除", "取消");
		// cd.show();
		return true;
	}

	// @Override
	// public void onItemClick(AdapterView<?> arg0, View arg1, int position,
	// long arg3) {
	// RequestParams params = new RequestParams();
	// params.addBodyParameter("messageIds", datas.get(position).messageId);
	// onRequest(READED, UrlConstant.READED, HttpMethod.GET, params);
	// idStrings.add(datas.get(position).messageId);
	// }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// if (requestCode == READED && resultCode == RESULT_OK) {
		// datas.get(delPosition).unread = false;
		// mAdapter.notifyDataSetChanged();
		// }

	}

	@Override
	public void onMsgSelect(List<String> MsgId) {
		idStrings.addAll(MsgId);
	}

}
